<?php
//////////////////////////////////////////////////////////////////////////

//

//  File:		userAccess.class.php

//  Desc:		Database access object ps_DB

//  Author:		Carl Wells

//  Date:		10 Jan 2007. 

//  Notes:		php 4

//

///////////////////////////////////////////////////////////////////////////

class userAccess {



var $referPage;			// DEFAULT REFER PAGE. SET IN CONSTRUCTOR

var $error_message;		// CURRENT ERROR MESSAGE

var	$id;				// USER ID FROM DATABASE. SET IN selectUser();

var $name;				// USERNAME FROM DATABASE. SET IN selectUser();

var	$unit_number;		// UNIT NUMBER FROM DATABASE. SET IN selectUser();

var	$address;			// ADDRESS FROM DATABASE. SET IN selectUser();

var	$email;				// EMAIL ADDRESS FROM DATABASE. SET IN selectUser();

var	$quantities;		// QUANTITIES SAVED FROM EARLIER;

var $loggedIn;			// FLAG TO SHOW IF USER IS LOGGED IN


//constructor
function userAccess(){
	define("HOMEPAGE", "home.php");
	
	define("NOT_AUTH", "http://www.ocstoolbox.co.uk/noauth.php");
	
	define("LOGINPAGE", "index.php");
	
	define("USERLOGIN","user_login");
	
	define("USERPROFILE","user_profile");

	//$this->referPage = 'index.php';
}

// check to see if the user is logged in
// i.e there is a session with variable 'loggedIn'
// loggedIn == TRUE
function isLoggedIn($level){
	if ($_SESSION['loggedIn'] != NULL){
		if ($_SESSION['loggedIn'] == TRUE){
			$this->checkAccessLevel($level);
		}else{
		header("Location:".LOGINPAGE);
		}
	
	}else{
		header("Location:".LOGINPAGE);
	}
	
	/*
	if ( $_SESSION['loggedIn'] == TRUE ){ //we arelogged in
		$this->checkAccessLevel($level);
	}else{
		// send to login page
		header("Location".LOGINPAGE);
		return FALSE;
	}
	*/
}
function login($username, $password){

	if ($_POST['username']==''){
	
		$this->error_message = $this->error(2);
		
		return;
	}
	
	if ($_POST['password']==''){
	
		$this->error_message = $this->error(3);
		
		return;
	}
	
	
	$password = md5($password);
	
	
	$sql = sprintf("SELECT * FROM `%s` WHERE `username` = '%s' AND `password` = '%s'", USERLOGIN, $username, $password);
	
	$db = new Connection();
	$login_res = $db->selectQuery($sql);
	
	$num_rows = mysql_num_rows($login_res);
	
	if ($num_rows>0){
	
	$_SESSION['loggedIn'] = true;
	
	$user_obj = mysql_fetch_assoc($login_res);
	
	$id =  $user_obj['id'];
	
	$level =  $user_obj['accessLevel'];
	
	//$email =  $user_obj['email'];
	
	$realname =  stripslashes($user_obj['firstname'])." ".stripslashes($user_obj['lastname']);
	
	
	$sql = sprintf("SELECT * FROM `%s` WHERE `loginId` = '%s'", USERPROFILE, $id);
	
	$profile_res = $db->selectQuery($sql);
	
	$profile_obj = mysql_fetch_assoc($profile_res);
	$lob =  $profile_obj['lob'];
	
		
	$_SESSION['userId'] = $id;
	
	$_SESSION['level'] = $level;
	
	//$_SESSION['email'] = $email;
	
	$_SESSION['username'] = $username;
	
	$_SESSION['realname'] = $realname;
	
	$sql = "SELECT `session_id` FROM `login_in_record` WHERE `session_id` = '".session_id()."';";
	$result = $db->selectQuery($sql);
	if (mysql_num_rows($result) > 0 ){
	
		session_regenerate_id(TRUE);
	}
	
	
	$_SESSION['ct_session_id'] = session_id();
	
	
	
	$_SESSION['lob'] = $lob;
	
	
	$sql = ("INSERT INTO `login_in_record` VALUES ('', '".$username."', '".$_SESSION['ct_session_id']."', 0, '".time()."'  )" );
	$insertLoginRecord = $db->selectQuery($sql);
	
	
	
	//insert the login data into the database
	$date = date ("jS F Y", time());
	
	$time = time();
	
	//header("Location:".$_SESSION['referPage']);
	
	header("Location:".HOMEPAGE);
	
	$this->error_message = $this->error(5);
	
	// ////////////////////
	// UNCOMMENT FOR LOGGING USER ACTIVITY
	// ////////////////////
	
	//$sql = sprintf("INSERT INTO `sol_user_log` VALUES ('', '%s', '%s', '%s', '%s' );", $id, $date, $time, session_id());
//	$login_insert = mysql_query($sql,$conn->conn) or die (mysql_error());



//		if ($login_insert){
		
//			if (isset($_SESSION['referPage'])){
			/* echo ($_SESSION['referPage']."<br/>");
			echo ("IS SET");
			exit; */
			
//			header("Location:".$_SESSION['referPage']);
//			}else{
			//echo ("Not SET");
			//exit;
//			header("Location:home.php");
//			}
//		}else{
//		$this->error_message = $this->error(1);
//		}
//	}else{
//	$this->error_message = $this->error(4);
//	}
	}else{
	
	$this->error_message = $this->error(4);
	}
	
}

/**
   * checkAccessLevel():
   * Called from $this->isLoggedIn(0)
   * When a user is logged in their Access Level is retrieved
   * from the database and stored in a session
   *
   * @param   $level   The access level from isLoggedIn
   */
function checkAccessLevel($level){

	if (isset($_SESSION['level'])){ //set when logged in
		if ($_SESSION['level'] < $level){
		//echo ("ACCESS LEVEL : Not authorised");
		header("Location:".NOT_AUTH);
		}
	}
}


/**
   * selectUser();
   * Gets the user information from the database
   * and populates the object
   *
   * @param   $conn   A mysql database connection resourse
   */
function selectUser($conn){
	
	$id = ($_SESSION['user_id']);
	
	$sql = sprintf("SELECT * FROM `%s` WHERE `user_id` = '%s'", USERTABLE, $id);
	
	$login_res = mysql_query($sql,$conn->conn) or die (mysql_error());
	
	$user_details = mysql_fetch_object($login_res);

	$this->id = $user_details->user_id;
	
	$this->name = $user_details->username;
	
	$this->unit_number = $user_details->unit_number;
	
	$this->address = $user_details->address;
	
	$this->email = $user_details->email;
}


/**
   * selectUser();
   * Gets the user information from the database
   * and populates the object
   *
   * @param   $conn   A mysql database connection resourse
   */
function logout(){

	$_SESSION = array();

	// If it's desired to kill the session, also delete the session cookie.
	// Note: This will destroy the session, and not just the session data!
	if (isset($_COOKIE[session_name()])) {
	
		setcookie(session_name(), '', time()-42000, '/');
		
	}

	// Finally, destroy the session.
	
	session_destroy();
	
	header ("Location:".HOMEPAGE);


}

function error($num){

	switch ($num){
		case 1:
		$msg = 'Unable to log you in. Please contact your unit manager.';
		break;
		case 2:
		$msg = 'Username is required.';
		break;
		case 3:
		$msg = 'Password is required.';
		break;
		case 4:
		$msg = 'Your username or password is incorrect.<br/>Please check your spelling.<br/>Usernames and passwords are case sensitive';
		break;
		case 5:
		$msg = 'Logged in';
		break;
	}

	return $msg;

	}


}
?>